//
//  MeetingManager.swift
//  EyeVisionForDoctors
//
//  Created by PMC on 2020/2/19.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import AVFoundation

enum YSGMeetingStatus {
    case none
    case disConnected
    case connected
    case connecting
}

protocol YSGVideoManagerPotocol {
    var meetingViewController: YSGMeetingViewController? { get set }
    /// 初始化
    func initSDK()
    /// 登录
    func loginSDK(account: String, password: String)
    /// 退出登录
    func logoutSDK()
    /// 拨号
    func dialNumber(number: String, name: String)
    /// 接听当前会话
    func acceptCall()
    /// 拒绝当前会话
    func rejectCall()
    /// 挂断
    func hangup()
    /// 视频开始的准备
    func startVideo()
    /// 视频结束处理
    func endVideo()
    /// 设置本地摄像头
    func setLocalVideo()
    /// 切换视频/语音模式
    func audio(enable: Bool)
    /// 静音
    func mute(enable: Bool)
    /// 切换摄像头
    func camera(enable: Bool)
}

class MeetingManager: NSObject {
    static let shared = MeetingManager()
    private(set) var manager: YSGVideoManagerPotocol?
    override init() {
        super.init()
        manager = YSGNemoSDK()
        initSDK()
        loginSDK()
        
        checkCamera()
        checkMicrophone()
    }
    
    @discardableResult
    public class func create() -> MeetingManager {
        return MeetingManager.shared
    }
    
    public weak var meetingViewController: YSGMeetingViewController? {
        didSet {
            manager?.meetingViewController = meetingViewController
        }
    }
    
    public func initSDK() {
        manager?.initSDK()
    }
    /// 登录账号
    public func loginSDK() {
        let videoAccountDTO = UserDefaults.videoAccountDTO
        guard let account = videoAccountDTO?.account,
              let password = videoAccountDTO?.password else { return }
        manager?.loginSDK(account: account, password: password)
    }
    /// 挂断
    public func endMeeting() {
        manager?.hangup()
    }
    /// 拨打给患者
    public func startMeeting(model: MeetingLoginModel, displayName: String) {
        guard let data = model.data else { return }
        manager?.dialNumber(number: data, name: displayName)
    }
    
    public func checkCamera() {
        DispatchQueue.main.async {
            let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
            switch authStatus {
            case .notDetermined:
                self.checkCameraPermission()
            case .restricted, .denied:
                AlertTool.showAlert(mainWindow.rootViewController!, title: "无法访问您的相机", message: "请到设置 -> 隐私 -> 相机，打开访问权限", sureTitle: "知道了")
            case .authorized:
                break
            default: break
            }
        }
    }
    
    private func checkCameraPermission () {
        AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { granted in
            if !granted {
                AlertTool.showAlert(mainWindow.rootViewController!,
                                    title: "无法访问您的相机",
                                    message: "请到设置 -> 隐私 -> 相机，打开访问权限",
                                    sureTitle: "知道了")
            }
        })
    }
    
    private func checkMicrophone() {
        DispatchQueue.main.async {
            RecordManager.sharedInstance.requestAuthorizations { (sucess) in
                if !sucess {
                    AlertTool.showAlert(mainWindow.rootViewController!,
                                        message: "需要访问您的麦克风\n请启用麦克风-设置-隐私-麦克风",
                                        sureTitle: "去打开",
                                        cancelTitle: "取消",
                                        type: .double,
                                        sureHandler: { (action) in
                        SettingTools.openAppSetting()
                    })
                }
            }
        }
    }
}

class AudioPlayerManager: NSObject {
    static let sharedInstance = AudioPlayerManager()
    var audioPlayer: AVAudioPlayer?

    private func setSession(type: AVAudioSession.Category) -> Bool {
        let session = AVAudioSession.sharedInstance()
        var result = false

        do{
            try session.setCategory(type)
            result = true
        } catch let err{
            print("session设置类型失败:\(err.localizedDescription)")
            result = false
        }

        do {
            try session.setActive(true)
            result = true
        } catch let err {
            print("session初始化动作失败:\(err.localizedDescription)")
            result = false
        }

        return result
    }

    func play() {
        guard setSession(type: .playback) else { return }
        let path = Bundle.main.path(forResource: "ring_back", ofType: "wav")!
        let url = URL(fileURLWithPath: path)
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer?.numberOfLoops = -1
            audioPlayer?.prepareToPlay()
        } catch let err {
            print("audioPlayer初始化动作失败:\(err.localizedDescription)")
        }
        audioPlayer?.play()
    }

    func stop() {
        guard audioPlayer != nil else { return }
        audioPlayer?.stop()
        audioPlayer = nil
    }
}

import HandyJSON

struct MeetingLoginModel: HandyJSON {
    var data: String?
}
